package com.android.djlmapp.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.tools.global.ToastUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportActivity;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 自定义扫码界面
 */
@RuntimePermissions
public class BarCodeScanerActivity extends SupportActivity {

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar_code_scaner);
        ButterKnife.bind(this);
        initSet();

        initView();
        BarCodeScanerActivityPermissionsDispatcher.needpermissionWithCheck(BarCodeScanerActivity.this);
    }

    private void initSet() {
        // 防止软键盘影响布局
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色;
                .statusBarColor(R.color.scan_title_color)
                .init();
    }

    protected void initView() {
        tvName.setText("扫一扫");
    }

    protected void initData() {
        /**
         * 执行扫面Fragment的初始化操作
         */
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);

        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {

            Log.e("项目异常BarCoity", "------onAnalyzeSuccess------" + result);
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
            bundle.putString(CodeUtils.RESULT_STRING, result);
            resultIntent.putExtras(bundle);
            setResult(0, resultIntent);
            finish();
        }

        @Override
        public void onAnalyzeFailed() {
            Log.e("项目异常BarCoctivity", "------onAnalyzeFailed------");
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "扫描失败");
            resultIntent.putExtras(bundle);
            setResult(0, resultIntent);
            finish();
        }
    };

    @OnClick(R.id.ll_top_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 如果你的app可以横竖屏切换，并且适配4.4或者emui3手机请务必在onConfigurationChanged方法里添加这句话
        ImmersionBar.with(this).init();
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void needpermission() {
        initData();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BarCodeScanerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA})
    void showRational(final PermissionRequest request) {
        new AlertDialog.Builder(BarCodeScanerActivity.this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取摄像头权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void Denied() {
        Log.e("权限", "------denied------");
        ToastUtils.showShortToast(BarCodeScanerActivity.this, "权限不足,您没有开启此应用的摄像头权限。请到系统设置-->权限管理 开启摄像头权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！");
        finish();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA})
    void AskAgin() {
        Log.e("权限", "------AskAgin------");
        ToastUtils.showShortToast(BarCodeScanerActivity.this, "权限不足,您没有开启此应用的摄像头权限。请到系统设置-->权限管理 开启摄像头权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！");
        finish();
    }
}
